/**
 * @license
 * Copyright Alibaba.com All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */

import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
  ViewEncapsulation
} from '@angular/core';

import { isNotNil,  InputBoolean, ApesUpdateHostClassService } from '@shared/apes/core';

@Component({
  // tslint:disable-next-line:component-selector
  selector: 'td:not(.apes-disable-td):not([mat-cell])',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [ApesUpdateHostClassService],
  preserveWhitespaces: false,
  encapsulation: ViewEncapsulation.None,
  templateUrl: './apes-td.component.html',
  host: {
    '[style.left]': 'apesLeft',
    '[style.right]': 'apesRight',
    '[style.text-align]': 'apesAlign'
  }
})
export class ApesTdComponent implements OnChanges {
  @Input() apesChecked = false;
  @Input() apesDisabled = false;
  @Input() apesIndeterminate = false;
  @Input() apesLeft: string;
  @Input() apesRight: string;
  @Input() apesAlign: 'left' | 'right' | 'center';
  @Input() apesIndentSize: number;
  @Input() @InputBoolean() apesExpand = false;
  @Input() @InputBoolean() apesShowExpand = false;
  @Input() @InputBoolean() apesShowCheckbox = false;
  @Output() readonly apesCheckedChange = new EventEmitter<boolean>();
  @Output() readonly apesExpandChange = new EventEmitter<boolean>();

  expandChange(e: Event): void {
    e.stopPropagation();
    this.apesExpand = !this.apesExpand;
    this.apesExpandChange.emit(this.apesExpand);
  }

  setClassMap(): void {
    this.apesUpdateHostClassService.updateHostClass(this.elementRef.nativeElement, {
      [`apes-table-row-expand-icon-cell`]: this.apesShowExpand && !isNotNil(this.apesIndentSize),
      [`apes-table-selection-column`]: this.apesShowCheckbox,
      [`apes-table-td-left-sticky`]: isNotNil(this.apesLeft),
      [`apes-table-td-right-sticky`]: isNotNil(this.apesRight)
    });
  }

  constructor(private elementRef: ElementRef, private apesUpdateHostClassService: ApesUpdateHostClassService) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.apesIndentSize || changes.apesShowExpand || changes.apesShowCheckbox || changes.apesRight || changes.apesLeft) {
      this.setClassMap();
    }
  }
}
